package com.yitiao.multithread;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.*;

/**
 * 防止线程创建个销毁的开销
 * 合理复用线程，计划经济
 * - 七大参数
 * - 线程工厂？？
 * - 默认工厂  Executors.defaultThreadFactory()  创建的线程在同一线程组，同一优先级，不会有守护线程
 * - keepAliveTime 线程空闲的时间被回收 核心线程不会回收
 * - 拒绝策略
 * - 创建线程池
 * - 阿里规范线程池
 * - 阻塞队列
 * - 队列的选择
 * - 线程数的选择
 * - 源码
 *
 * @author libiao
 */
public class MyThreadPool {

//    static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static void main(String[] args) {
//        createdThreadPool();
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 100; i++) {
            int finalI = i;
            fixedThreadPool.submit(new Thread(() -> {
                System.out.println(Thread.currentThread().getName() +
                        " --- " +
                        safeFormat.formatThreadLocal.get().format(new Date(1000L * (1000L + finalI))));
            }, "thread-" + i));
        }
        fixedThreadPool.shutdown();
    }

    private static void createdThreadPool() {
        ThreadFactory threadFactory = Executors.defaultThreadFactory();

        new SynchronousQueue<>();
        new LinkedBlockingDeque<>();
        new ArrayBlockingQueue<>(10);

        // 固定数量的线程池
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 100; i++) {
            executorService.execute(
                    new Thread(() -> {
                        System.out.println(Thread.currentThread().isDaemon());
                    }, "123")
            );
        }

//          只有一个线程
        Executors.newSingleThreadExecutor();
    }


    /**
     * 两个线程的SimpleDataFormat
     */
//    private static String dataTransfer(int seconds) {
//        // 加锁版
////        String format="";
////        synchronized (MyThreadLocal.class){
////            format = dateFormat.format(new Date(1000L * seconds));
////        }
////        return format;
//
//    }
    private static String dataTransfer(int seconds) {
        // 加锁版
//        String format="";
//        synchronized (MyThreadLocal.class){
//            format = dateFormat.format();
//        }
        return safeFormat.formatThreadLocal.get().format(new Date(1000L * seconds));

    }

}

class safeFormat {
    static ThreadLocal<SimpleDateFormat> formatThreadLocal = ThreadLocal.withInitial(() ->
            new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
    );
}
